package com.cskaoyan.wordmemorize.common.upload;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.cskaoyan.wordmemorize.service.FileUploadService;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Slf4j
@Service
@ConditionalOnBean(AliOssProperties.class)
public class AliOssStorageServiceImpl implements FileUploadService {
    @Resource
    private AliOssProperties aliOssProperties;


    /**
     * 文件上传
     */
    @Override
    public String upload(MultipartFile file) throws IOException {
        String endpoint = "https://oss-cn-wuhan-lr.aliyuncs.com";
        String accessKeyId = "LTAI5tMVgco2hSnwZ4mCRakP";
        String accessKeySecret = "lRUj1QeESpX83cnJJeqLGVXVoPBoDB";
        String bucketName = "wangdao-words";

        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID() + extension;

        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        StringBuilder stringBuilder = new StringBuilder("https://");
        try {
            // 向桶中放入指定名称的对象
            ossClient.putObject(bucketName, objectName, file.getInputStream());

            //文件访问路径规则 https://BucketName.Endpoint/ObjectName
            stringBuilder.append(bucketName)
                    .append(".")
                    .append(endpoint.substring(endpoint.lastIndexOf("/") + 1))
                    .append("/")
                    .append(objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }

        // 返回访问文件的url
        return stringBuilder.toString();

    }

    @Override
    public void deleteFile(String objectName)  {
        String endpoint = "https://oss-cn-wuhan-lr.aliyuncs.com";
        String accessKeyId = "LTAI5tMVgco2hSnwZ4mCRakP";
        String accessKeySecret = "lRUj1QeESpX83cnJJeqLGVXVoPBoDB";
        String bucketName = "wangdao-words";

        // 创建 OSSClient 实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 删除桶中指定对象  objectName: 文件名  取请求参数文件访问路径最后一个/后面的值
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException oe) {
            log.error("阿里OSS异常，Error Message:{}", oe.getErrorMessage());
        } catch (ClientException ce) {
            log.error("阿里OSS Client异常，Error Message:{}", ce.getMessage());
        } finally {
            if (!ObjectUtils.isEmpty(ossClient)) {
                ossClient.shutdown();
            }
        }
    }
}
